import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:get/get.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/form_utils.dart';

/// 协销表单
class AssistFormWidget extends StatefulWidget {
  final String? uId;

  const AssistFormWidget({super.key, this.uId});

  @override
  State<AssistFormWidget> createState() => _AssistFormState();
}

class _AssistFormState extends State<AssistFormWidget> {
  RequestRepository repository = Get.find<RequestRepository>();
  final _formKey = GlobalKey<FormBuilderState>();

  bool assistSaleFlag = false; // 是否达标

  late TextEditingController _porductController;
  late TextEditingController _amountController;
  late TextEditingController _countController;
  late TextEditingController _assistTeacherController;
  late TextEditingController _dateController;
  late TextEditingController _reasonController;

  late FocusNode _porductFocusNode;
  late FocusNode _amountFocusNode;
  late FocusNode _countFocusNode;
  late FocusNode _assistTeacherFocusNode;
  late FocusNode _dateFocusNode;
  late FocusNode _reasonFocusNode;

  @override
  void initState() {
    super.initState();
    _porductController = TextEditingController();
    _amountController = TextEditingController();
    _countController = TextEditingController();
    _assistTeacherController = TextEditingController();
    _dateController = TextEditingController();
    _reasonController = TextEditingController();

    _porductFocusNode = FocusNode();
    _amountFocusNode = FocusNode();
    _countFocusNode = FocusNode();
    _assistTeacherFocusNode = FocusNode();
    _dateFocusNode = FocusNode();
    _reasonFocusNode = FocusNode();

    _formKey.currentState?.patchValue({
      'assistSaleFlag': assistSaleFlag, // 设置新的值
    });
  }

  @override
  void dispose() {
    _porductController.dispose();
    _amountController.dispose();
    _countController.dispose();
    _assistTeacherController.dispose();
    _dateController.dispose();
    _reasonController.dispose();

    _porductFocusNode.dispose();
    _amountFocusNode.dispose();
    _countFocusNode.dispose();
    _assistTeacherFocusNode.dispose();
    _dateFocusNode.dispose();
    _reasonFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text('新增协销数据'),
        ),
        body: SingleChildScrollView(
          child: FormBuilder(
            key: _formKey,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                  FormBuilderTextField(
                    name: 'product',
                    keyboardType: TextInputType.text,
                    decoration: const InputDecoration(labelText: '销售产品'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入销售产品'),
                    ]),
                    controller: _porductController,
                    focusNode: _porductFocusNode,
                    textInputAction: TextInputAction.next,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_amountFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'amount',
                    keyboardType: TextInputType.number,
                    decoration: const InputDecoration(labelText: '销售金额'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入销售金额'),
                      FormBuilderValidators.numeric(errorText: '请输入数字'),
                    ]),
                    textInputAction: TextInputAction.next,
                    controller: _amountController,
                    focusNode: _amountFocusNode,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_countFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'count',
                    keyboardType: TextInputType.number,
                    decoration: const InputDecoration(labelText: '销售数量'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请输入销售数量'),
                      FormBuilderValidators.numeric(errorText: '请输入数字'),
                    ]),
                    textInputAction: TextInputAction.next,
                    controller: _countController,
                    focusNode: _countFocusNode,
                    onEditingComplete: () {
                      FocusScope.of(context).requestFocus(_assistTeacherFocusNode);
                    },
                  ),
                  FormBuilderTextField(
                    name: 'assistTeacher',
                    textInputAction: TextInputAction.done,
                    focusNode: _assistTeacherFocusNode,
                    decoration: const InputDecoration(labelText: '协助讲师'),
                    controller: _assistTeacherController,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  FormBuilderTextField(
                    name: 'date',
                    readOnly: true,
                    decoration: const InputDecoration(labelText: '日期'),
                    validator: FormBuilderValidators.compose([
                      FormBuilderValidators.required(errorText: '请选择日期'),
                    ]),
                    controller: _dateController,
                    focusNode: _dateFocusNode,
                    onTap: () {
                      openDatePicker(context, DateItemKind.orderDate, (value) {
                        _dateController.text = value;
                      });
                    },
                  ),
                  FormBuilderSwitch(
                    name: 'assistSaleFlag',
                    initialValue: assistSaleFlag,
                    selected: assistSaleFlag,
                    title: Text('是否达标'),
                    onChanged: (value) {
                      assistSaleFlag = value ?? false;
                    },
                  ),
                  FormBuilderTextField(
                    name: 'reason',
                    textInputAction: TextInputAction.done,
                    focusNode: _reasonFocusNode,
                    decoration: const InputDecoration(labelText: '不达标原因'),
                    controller: _reasonController,
                    onEditingComplete: () {
                      FocusScope.of(context).unfocus();
                    },
                  ),
                  SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: () {
                      //{"customerInfoId":"1877280757693566976","product":"121","amount":"23.4","num":"3","assistTeacher":"1222222","date":"2025-01-07T16:00:00.000Z","assistSaleFlag":false,"reason":"34"}
                      /// 验证表单
                      if (!_formKey.currentState!.saveAndValidate()) {
                        return;
                      }

                      /// 提交数据
                      Map<String, dynamic> map = {
                        "customerInfoId": widget.uId,
                        "product": _porductController.text,
                        "amount": _amountController.text,
                        "num": _countController.text,
                        "assistTeacher": _assistTeacherController.text,
                        "date": _dateController.text,
                        "assistSaleFlag": assistSaleFlag,
                        "reason": _reasonController.text,
                      };
                      repository.addDistributorAssist(
                          params: map,
                          success: (data) {
                            Navigator.pop(context, true);
                          },
                          fail: (code, msg) {});
                    },
                    child: const Text('保存'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
